package com.hz.ruoyilgorder.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.hz.rouyigonggong.domain.LgInboundOrder;
import com.hz.rouyigonggong.domain.LgSellerOrder;
import com.hz.rouyigonggong.domain.basedomain.BaseDomain;
import com.hz.rouyigonggong.domain.dto.LgDriverLogisticsDTO;
import com.hz.rouyigonggong.domain.dto.LgSellerOrderDTO;
import com.hz.ruoyilgorder.api.service.LgCar;
import com.hz.ruoyilgorder.api.service.SubColdSome;
import com.hz.ruoyilgorder.config.LgSellerOrderConverter;
import com.hz.ruoyilgorder.mapper.LgSellerOrderDTOMapper;
import com.hz.ruoyilgorder.mapper.LgSellerOrderMapper;
import com.hz.ruoyilgorder.rabbitmq.RabbitMQConfig;
import com.hz.ruoyilgorder.service.LgDriverLogisticsService;
import com.hz.ruoyilgorder.service.LgInboundOrderService;
import com.hz.ruoyilgorder.service.LgSellerOrderService;
import com.hz.ruoyilgorder.utils.ResultJSON;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.datasource.annotation.Master;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @version 1.0
 * @Author yzw
 * @Date 2025/3/5 9:42
 * @注释  卖家寄冷库 订单管理
 */
@RestController
@RequestMapping("/order")
public class LgSellerOrderController {
    @Autowired
    private LgSellerOrderService lgSellerOrderService;
    @Autowired
    private LgDriverLogisticsService lgDriverLogisticsService;
    @Autowired
    private LgInboundOrderService lgInboundOrderService;
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private LgSellerOrderDTOMapper lgSellerOrderDTOMapper;

    @Autowired
    private LgCar lgCar;
    @Autowired
    private SubColdSome subColdSome;


    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/getpaihang")
    //@GlobalTransactional//分布式事务
    public ResultJSON getColdCount(){
        if(redisTemplate.opsForValue().get("coldCount") == null){
            List list = subColdSome.getColdCount();
            redisTemplate.opsForValue().set("coldCount",list,1, TimeUnit.HOURS);
            return ResultJSON.success(redisTemplate.opsForValue().get("coldCount"));
        }
        return ResultJSON.success(redisTemplate.opsForValue().get("coldCount"));

    }


    @PostMapping("/addFinalGoodsPriceAndFinalFreightPrice")
    public AjaxResult addFinalGoodsPriceAndFinalFreightPrice(LgSellerOrder lgSellerOrder){
        System.out.println("**************"+lgSellerOrder);
    return AjaxResult.success(lgSellerOrderMapper.updateById(lgSellerOrder));
    }
    /**
    * @Description: 通过orderId，改变订金状态
    * @Param: [orderId, depositPaid]
    * @Param: [orderId, depositPaid]
    * @return: com.ruoyi.common.core.web.domain.AjaxResult
    * @Author: grx
    * @Date: 14:28 2025/3/15
    */
@PostMapping("updateDepositStatus")
public AjaxResult updateDepositStatus( Integer orderId,Integer depositPaid){
    UpdateWrapper<LgSellerOrder> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id",orderId);
    updateWrapper.set("deposit_paid",depositPaid);
    return AjaxResult.success(lgSellerOrderService.update(updateWrapper));
}
    /**
     * @Description: app，通过重量和距离算运费
     * @Param: [sellerId]
     * @return: com.ruoyi.common.core.web.domain.AjaxResult
     * @Author: grx
     * @Date: 11:51 2025/3/14
     */


    @GetMapping("/getColdPrice")
    //priceMeter 价格（每立方米每天价格）
    //dailyPrice 单日价格(容积×冷库类型价格）
    public AjaxResult getColdPrice(Integer storageDays, Double dailyPrice){

        double totalPrice = storageDays*dailyPrice;
        return AjaxResult.success(totalPrice);
    }
    @GetMapping("/getDriverPrice")
    public AjaxResult getDriverPrice(Double weight, Double distance){

        // 起步价定义（例如：500元）
        final double basePrice = 500.0;

        // 每公里的单价（例如：6元/公里）
        final double pricePerKm = 6.0;

        // 每公斤的单价（例如：5元/公斤）
        final double pricePerKg = 5.0;

        // 计算费用
        double totalPrice = (pricePerKm * distance) + (pricePerKg * weight);
        totalPrice = Double.parseDouble(String.format("%.2f", totalPrice));
        if (totalPrice < basePrice){
            totalPrice = basePrice;
        }
        return AjaxResult.success(totalPrice);
    }

    /**
     * @Description: app，通过订单id查找对应的订单
     * @Param: [sellerId]
     * @return: com.ruoyi.common.core.web.domain.AjaxResult
     * @Author: grx
     * @Date: 11:51 2025/3/14
     */

    @GetMapping("/getLgSellerOrderById")

    public AjaxResult getOrderById(Integer orderId){
        return AjaxResult.success(lgSellerOrderService.getLgSellerOrderById(orderId));
    }

    /**
    * @Description: app，通过卖家id查找他的订单
    * @Param: [sellerId]
    * @return: com.ruoyi.common.core.web.domain.AjaxResult
    * @Author: grx
    * @Date: 11:51 2025/3/14
    */

    @GetMapping("/getLgSellerOrderBySellerId")
    public AjaxResult getLgSellerOrderBySellerId(Integer sellerId){
//        QueryWrapper<LgSellerOrder> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("seller_id",sellerId);
//        queryWrapper.orderByDesc("create_time");

        return AjaxResult.success(lgSellerOrderService.getLgSellerOrderBySellerId(sellerId));
    }



    protected void startPage()
    {
        PageUtils.startPage();
    }
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
    @RequiresPermissions("order:every:list")
    @GetMapping("/getlist")
    public TableDataInfo getLgSellerOrderList(LgSellerOrderDTO entity){
        startPage();
        //赋值创建人
        entity.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        List<LgSellerOrderDTO> list= lgSellerOrderService.getLgSellerOrderList(entity);
        return getDataTable(list);
    }

    /**
     * 根据订单id获取详细信息
     */
    @RequiresPermissions("order:every:query")
    @GetMapping(value = "/getInfo/{orderNumber}")
    public AjaxResult getInfo(@PathVariable Integer orderNumber) {

        return AjaxResult.success(lgSellerOrderService.getInfo(orderNumber));
    }

    @RequiresPermissions("order:every:edit")
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody  LgSellerOrderDTO orderDTO) {
        //转换
        LgSellerOrder order = LgSellerOrderConverter.toEntity(orderDTO);
        //当余款支付完成时 ，入库订单改为入库中
        if(order.getDepositPaid()==7){
            Wrapper<LgInboundOrder> lgSellerOrderWrapper = new QueryWrapper<LgInboundOrder>()
                    .eq("order_number", orderDTO.getOrderNumber());
            LgInboundOrder lgInboundOrder = new LgInboundOrder();
            lgInboundOrder.setStatus(3);
            lgInboundOrderService.update(lgInboundOrder, lgSellerOrderWrapper);
        }
        return AjaxResult.success(lgSellerOrderService.updateById(order));
    }
    //添加
    @RequiresPermissions("order:every:add")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody  LgSellerOrderDTO orderDTO) {

        LgSellerOrder order = LgSellerOrderConverter.toEntity(orderDTO);
            Integer subId =order.getSubId();
            String createBy = subColdSome.getCreateBy(subId);
            order.setCreateBy(createBy);//orderDTO.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        System.out.println("orderDTO:"+createBy);
        if(order.getSubId()!=null){
           // System.out.println("兼容机");
            System.out.println("subId:"+subId);
            String yunsuan="-";
            //调接口减去剩余容积
            subColdSome.updateCold(subId,yunsuan);
        }
        return  AjaxResult.success(lgSellerOrderService.save(order));
    }
        @PostMapping("/addQuxiao")
    public AjaxResult addQuxiao(@Validated @RequestBody  LgSellerOrderDTO orderDTO) {
        String message = String.valueOf(orderDTO.getOrderNumber());

            rabbitTemplate.convertAndSend(RabbitMQConfig.NORMAL_EXCHANGE, RabbitMQConfig.NORMAL_QUEUE,message,new MessagePostProcessor(){
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    // 设置5s过期
                    message.getMessageProperties().setExpiration("10000");
                    return message;
                }
            });
            System.out.println("发送消息："+orderDTO);
        LgSellerOrder order = LgSellerOrderConverter.toEntity(orderDTO);
        if(order.getSubId()!=null){
            System.out.println("兼容机");

            Integer subId =order.getSubId();
            System.out.println("subId:"+subId);
            String yunsuan="-";
            //调接口减去剩余容积
            subColdSome.updateCold(subId,yunsuan);
        }
        return  AjaxResult.success(lgSellerOrderService.save(order));
    }

    @RequiresPermissions("order:every:remove")
    @GetMapping("/remove/{ids}")
    @Master
    public AjaxResult remove(@PathVariable Long[] ids) {

        return AjaxResult.success(lgSellerOrderService.removeByIds(Arrays.asList(ids)));
    }
    //调用driver服务
    @RequiresPermissions("order:every:driver")
    @GetMapping("/getlistdriver")
   // @GlobalTransactional//分布式事务
    public AjaxResult getLgSellerOrderList(){
        startPage();
        Map<String, Object> params = new HashMap<>();
        // 可以根据实际需求加入查询条件
        params.put("status", 0); // 例如，查询激活状态的司机
        params.put("createBy",String.valueOf(BaseDomain.getUserId()) );
        return AjaxResult.success(lgCar.getAlldriver(params, 1, 10));
    }
    @RequiresPermissions("order:every:car")
    @GetMapping("/getlistcar")
    //@GlobalTransactional//分布式事务
    public AjaxResult getcar(Integer licenseType){
//        System.out.println(licenseType);
        startPage();

        return AjaxResult.success(lgCar.getAll(null,null,null,null,licenseType,0,1,10,String.valueOf(BaseDomain.getUserId()) ));
    }
    //指派司机
    @RequiresPermissions("order:every:driver")
    @PostMapping("/driver")
    public ResultJSON driver(@RequestBody Map<String, Object> body) {

        Integer orderNumber = (Integer) body.get("orderNumber");
        Integer driverId = (Integer) body.get("driverId");
        LgDriverLogisticsDTO lgDriverLogisticsDTO = new LgDriverLogisticsDTO();
        lgDriverLogisticsDTO.setLogisticsOrderNumber(orderNumber);
        lgDriverLogisticsDTO.setDriverId(driverId);
        lgDriverLogisticsDTO.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        if(lgDriverLogisticsService.adddriver(lgDriverLogisticsDTO)>=1){
            LgSellerOrder lgSellerOrder = new LgSellerOrder();
            lgSellerOrder.setDepositPaid(4);
            Wrapper<LgSellerOrder> lgSellerOrderWrapper = new QueryWrapper<LgSellerOrder>()
                    .eq("order_number", orderNumber);
            lgSellerOrderService.update(lgSellerOrder, lgSellerOrderWrapper);
            return  ResultJSON.success();
        }
        return  ResultJSON.error();

    }


    //指派车辆
    @RequiresPermissions("order:every:car")
    @PostMapping("/assignCar")
    public ResultJSON assignCar(@RequestBody Map<String, Object> body) {
        Integer orderNumber = (Integer) body.get("orderNumber");
        Integer carId = (Integer) body.get("carId");
        LgDriverLogisticsDTO lgDriverLogisticsDTO = new LgDriverLogisticsDTO();
        lgDriverLogisticsDTO.setLogisticsOrderNumber(orderNumber);
        lgDriverLogisticsDTO.setVehicleId(carId);
        lgDriverLogisticsDTO.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        if(lgDriverLogisticsService.add(lgDriverLogisticsDTO)==1){
            LgSellerOrder lgSellerOrder = new LgSellerOrder();
            lgSellerOrder.setDepositPaid(8);
            Wrapper<LgSellerOrder> lgSellerOrderWrapper = new QueryWrapper<LgSellerOrder>()
                    .eq("order_number", orderNumber);
            lgSellerOrderService.update(lgSellerOrder, lgSellerOrderWrapper);
            return  ResultJSON.success();
        }

        return  ResultJSON.error();
    }

        @Autowired
    private LgSellerOrderMapper lgSellerOrderMapper;
    //导出excel
    @RequiresPermissions("order:every:export")
    @Log(title = "订单列表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
//        System.out.println(response);
        // 1. 创建 ZIP 输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        // 2. 定义查询条件
        QueryWrapper<LgSellerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");  // 确保分页查询时数据稳定
        long totalRecords = lgSellerOrderMapper.selectCount(queryWrapper);
        int pageSize = 3;
        long totalPages = (totalRecords + pageSize - 1) / pageSize;

        // 3. 分页读取数据并压缩每个 Excel 文件
        for (int currentPage = 1; currentPage <= totalPages; currentPage++) {
            // 创建分页对象，查询当前页数据
            Page<LgSellerOrder> page = new Page<>(currentPage, pageSize);
            Page<LgSellerOrder> resultPage = lgSellerOrderMapper.selectPage(page, queryWrapper);
            List<LgSellerOrder> users = resultPage.getRecords();
            // 根据页码动态生成文件名
            String fileName = "lgsellerorder" + currentPage + ".xlsx";
            // 将 Excel 写入 ZIP
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOutputStream.putNextEntry(zipEntry);

            // 使用 EasyExcel 写入 Excel 文件数据
            ByteArrayOutputStream excelOutputStream = new ByteArrayOutputStream();
            EasyExcel.write(excelOutputStream, LgSellerOrder.class)
                    .sheet("数据")
                    .doWrite(users);
            zipOutputStream.write(excelOutputStream.toByteArray());
            zipOutputStream.closeEntry();
        }
        // 完成 ZIP 文件的写入
        zipOutputStream.finish(); // 确保写入完成
        zipOutputStream.close();  // 关闭输出流
//        // 保存 ZIP 文件到本地
//        File outputFile = new File("D://demo.zip");  // 设置保存路径
//        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
//            byteArrayOutputStream.writeTo(fileOutputStream);
//        }
        // 4. 设置响应头
        response.setHeader("Content-Disposition", "attachment; filename=lgsllerorder.zip");  // 设置文件名
        response.setContentType("application/octet-stream");  // 设置文件类型
        // 5. 将二进制数据写入响应
        response.getOutputStream().write(byteArrayOutputStream.toByteArray());
        response.flushBuffer();  // 确保数据立即发送
        }



    //调用仓库类型，大仓库和小仓库
    @GetMapping("/getColdSome")
    public ResultJSON getColdSome(){
        return ResultJSON.success(subColdSome.getColdSome());
    }
    //获取单位列表
    @RequestMapping("/getUnitAll")
    public ResultJSON getAll(){
        return ResultJSON.success(subColdSome.getAll());
    }
//调用仓库类型
    @GetMapping("/getColdType")
    public ResultJSON getColdType(){
        return ResultJSON.success(subColdSome.getColdType());
    }
    //调用仓库类型
    @GetMapping("/getParent")
    public ResultJSON getGoodsType(){
        return ResultJSON.success(subColdSome.getParent());
    }

    @GetMapping("/getParentId/{parentId}")
    public ResultJSON getParentId(@PathVariable Integer parentId){
        return ResultJSON.success(subColdSome.getChild(parentId));
    }
}
